<template>
  <el-tabs class="custom-tabs" v-model="activeName" @tab-change="handelClick">
    <el-tab-pane :label="$t('邮箱')" name="email"></el-tab-pane>
    <el-tab-pane :label="$t('手机号码')" name="mobile"></el-tab-pane>
  </el-tabs>
  <el-form
    ref="loginFormRef"
    :model="loginForm"
    status-icon
    :rules="rules"
    class="login-form"
  >
    <el-form-item prop="email" v-if="activeName === 'email'">
      <el-input
        v-model="loginForm.email"
        :placeholder="$t('请输入邮箱')"
        size="large"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="mobile" v-if="activeName === 'mobile'">
      <el-input
        v-model="loginForm.mobile"
        :placeholder="$t('请输入手机号码')"
        size="large"
        type="number"
        class="custom-input"
        @input="handleInput"
      >
        <template #prepend>
          <el-select
            v-model="loginForm.mobile_area_code"
            :placeholder="$t('区号')"
            size="large"
            style="width: 100px"
            class="custom-select"
            popper-class="custom-selectDropDown"
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <user />
              </el-icon>
            </template>
            <el-option
              v-for="item in options"
              :key="item.area_code"
              :label="item.label"
              :value="item.area_code"
            >
              <span>{{ item.country }}</span>
              <span>{{ item.area_code }}</span>
            </el-option>
          </el-select>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        type="password"
        v-model="loginForm.password"
        :placeholder="$t('请输入密码')"
        show-password
        @keyup.enter="onLogin"
        size="large"
        class="mt-2"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <!-- <el-form-item prop="captcha_input">
      <div class="flex items-center justify-between flex-1 mt-2">
        <el-input v-model="loginForm.captcha_input" :placeholder="$t('login.captcha')" size="large" style="width: 150px">
        </el-input>

        <div class="w-32 h-10 ml-2 cursor-pointer" @click="handleChangeCaptcha">
          <img :src="captchaSrc" alt="验证码加载中.." class="w-full h-full" ref="captcha" />
        </div>
      </div>
    </el-form-item> -->
  </el-form>
  <el-button
    size="large"
    type="primary"
    :icon="Monitor"
    class="w-full mt-2"
    :loading="loading"
    @click="onLogin"
  >
    {{ $t("登录") }}
  </el-button>
  <DialogForm
    @closeDialog="closeDialog"
    :dialogVisible="dialogVisible"
    @callApi="handleLoginGoogleApi"
  />
</template>
<script setup>
import { reactive, ref, computed, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { GetCaptcha, newLogin, getCountryArea } from "@/api/login/index";
import { useUserStore } from "@/store/modules/user";
import DialogForm from "../../settings/components/DialogForm.vue";
import { ElMessage } from "element-plus";
import { Monitor } from "@element-plus/icons-vue";
import { permissionsUserApi } from "@/api/merchant/index";
const loading = ref(false);
const loginFormRef = ref();
const dialogVisible = ref(false);
const router = useRouter();
const { t } = useI18n();
const useUser = useUserStore();

const activeName = ref("email");
const options = ref([]);
// let captchaSrc = ref(""); //验证码图片
const getAreaList = async () => {
  const res = await getCountryArea();
  options.value = res || [];
  loginForm.mobile_area_code = res[0].area_code || "";
};
getAreaList();
//获取验证码
// const getCaptcha = async () => {
//   try {
//     const res = await GetCaptcha();
//     captchaSrc.value = `${res.img_url}?${new Date().getTime()}`;
//   } catch (error) { }
// };
// getCaptcha();
// 切换验证码
// const handleChangeCaptcha = async () => {
//   getCaptcha();
// };
//获取验证码

// 打开窗口
const handleClickCreate = () => {
  dialogVisible.value = true;
};
// 关闭窗口
const closeDialog = () => {
  dialogVisible.value = false;
  loading.value = false;
};

const handleInput = (value) => {
  if (value.length > 16) {
    loginForm.mobile = value.slice(0, 16);
  } else {
    loginForm.mobile = value;
  }
};

// 校验
const rules = computed(() => {
  return {
    email: [{ required: true, message: t("请输入邮箱"), trigger: "blur" }],
    mobile: [
      { required: true, message: t("请输入手机号码"), trigger: "blur" },
      { min: 6, max: 16, message: t("请输入6-16位的数字"), trigger: "blur" },
    ],
    password: [{ required: true, message: t("请输入密码"), trigger: "blur" }],
    // captcha_input: [
    //   { required: true, message: t("login.captchaMessage"), trigger: "blur" },
    // ],
  };
});

const loginForm = reactive({
  email: "",
  mobile: "",
  mobile_area_code: "",
  password: "",
  // captcha_input: "",
});

const handelClick = () => {
  nextTick(() => {
    loginFormRef.value.resetFields();
  });
};
//登录
const onLogin = () => {
  loginFormRef.value
    .validate()
    .then(async () => {
      try {
        loading.value = true;
        loginForm.account_type = activeName.value;
        // 1.调用登录接口
        const res = await newLogin(loginForm);
        // // 2.更新用户信息到pinia

        useUser.setUserInfo({
          token: res.token.token,
          name: loginForm.email,
          expire: res.token.expire,
        });
        //获取权限
        const permissions = await permissionsUserApi();

        useUser.setPerm(permissions.perm);

        if (permissions.is_super == 1) {
          useUser.setPermissions(["all"]);
        } else {
          useUser.setPermissions(permissions.permissions);
        }

        // useUser.setPermissions({ token: res.token, });
        // 3.调整到首页
        router.replace("/");
        ElMessage({
          message: t("欢迎登录"),
          type: "success",
        });
      } catch (error) {
        console.error(error);
        const { data } = error;
        // console.log(data);
        loading.value = false;
        if (data.code == 10259) {
          handleClickCreate();
        }
      }
    })
    .catch((error) => {
      // console.log(error);
    });
};
// 验证码
const handleLoginGoogleApi = async (code) => {
  try {
    // 1.调用登录接口
    const res = await newLogin({ ...loginForm, google_code: code });

    useUser.setUserInfo({
      token: res.token,
      name: loginForm.email,
    });
    //获取权限
    const permissions = await permissionsUserApi();

    useUser.setPerm(permissions.perm);

    if (permissions.is_super == 1) {
      useUser.setPermissions(["all"]);
    } else {
      useUser.setPermissions(permissions.permissions);
    }

    ElMessage({
      message: t("欢迎登录"),
      type: "success",
    });
    // 3.调整到首页
    router.replace("/");
  } catch (error) {}
};
</script>
<style scoped></style>
